import { createSlice } from '@reduxjs/toolkit';
import { resetTabs } from './tabs';

// 从 localStorage 获取初始状态
const getInitialState = () => {
  try {
    const token = localStorage.getItem('token');
    const userInfo = localStorage.getItem('userInfo');
    const authElement = localStorage.getItem('authElement');
    return {
      token: token || null,
      userInfo: userInfo ? JSON.parse(userInfo) : null,
      authElement: authElement ? JSON.parse(authElement) : null,
    };
  } catch (error) {
    console.error('从 localStorage 读取用户信息失败:', error);
    return {
      token: null,
      userInfo: null,
      authElement: null,
    };
  }
};

//  检查用户是否已登录
export const isUserLoggedIn = () => {
  try {
    const token = localStorage.getItem('token');
    // 检查 token 是否存在且非空
    return token !== null && token !== undefined && token !== '';
  } catch (error) {
    console.error('检查用户登录状态失败:', error);
    return false;
  }
};

const userSlice = createSlice({
  name: 'user',
  initialState: getInitialState(),
  reducers: {
    setToken: (state, action) => {
      state.token = action.payload;
      // 同步到 localStorage
      if (action.payload) {
        localStorage.setItem('token', action.payload);
      } else {
        localStorage.removeItem('token');
      }
    },
    setUserInfo: (state, action) => {
      state.userInfo = action.payload;
      // 同步到 localStorage
      if (action.payload) {
        localStorage.setItem('userInfo', JSON.stringify(action.payload));
      } else {
        localStorage.removeItem('userInfo');
      }
    },
    setAuthElement: (state, action) => {
      state.authElement = action.payload;
      // 同步到 localStorage
      if (action.payload) {
        localStorage.setItem('authElement', JSON.stringify(action.payload));
      } else {
        localStorage.removeItem('authElement');
      }
    },
    logout: (state) => {
      state.token = null;
      state.userInfo = null;
      state.authElement = null;
      // 清除 localStorage
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('authElement');
    },
  }
});

// 登出时同时清空标签页状态
export const logoutAndResetTabs = () => (dispatch) => {
  dispatch(logout());
  dispatch(resetTabs());
};

export const { setToken, setUserInfo, setAuthElement, logout } = userSlice.actions;
export default userSlice.reducer;